//
//  VCtravles.m
//  project-A (pianke)
//
//  Created by dllo on 16/2/24.
//  Copyright © 2016年 scott. All rights reserved.
//

#import "VCtravles.h"
#import <AFNetworking.h>
#import "CellOfEssay.h"
#import "CellOfEssay2.h"
#import "ModelOfEssay.h"
#import "ViewXingCheng.h"
#import <DKNightVersion.h>


#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGH [UIScreen mainScreen].bounds.size.height

@interface VCtravles ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,retain)NSMutableDictionary *dic;

@property (nonatomic,retain)NSArray *array;



@property (nonatomic,assign)CGFloat xHeight;

@property (nonatomic,assign)CGFloat width;

@property (nonatomic,assign)CGFloat height;

@property (nonatomic,assign)CGFloat Lheight;

@property (nonatomic,retain)UIButton *button;

@property (nonatomic,retain)ViewXingCheng *xingcheng;

@property (nonatomic,retain)UILabel *labelxingcheng;

@property (nonatomic,retain)UIView *redline;

@property (nonatomic,retain)UIButton *Totop;

@property (nonatomic,retain)UITableView *tabviewxingcheng;


@end

@implementation VCtravles

-(void)dealloc{
    [_tabviewxingcheng release];
    [_button release];
    [_xingcheng  release];
    [_labelxingcheng release];
    [_dic release];
    [_array release];
    [_strURl release];
    [_redline release];
    [_Totop release];
    [super dealloc];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
        
    self.view.backgroundColor = [UIColor whiteColor];
    [self handleData];
    [self createTableView];
    
    [self creatxingchengview];
    
    [self hiddenStatusBar];
   
    self.labelxingcheng.dk_textColorPicker  = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.64 green:0.74 blue:0.86 alpha:1]);
    self.tabview.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
    
    
    UISwipeGestureRecognizer *swipeGr = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    
    [self.view addGestureRecognizer:swipeGr];
    swipeGr.direction = UISwipeGestureRecognizerDirectionLeft;
    
    [swipeGr release];
    
    UISwipeGestureRecognizer *swipeGr2 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped2:)];
    
    [self.view addGestureRecognizer:swipeGr2];
    swipeGr2.direction = UISwipeGestureRecognizerDirectionRight;
    
    [swipeGr2 release];
    
    
    
}


-(void)hiddenStatusBar
{
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)])
    {
        [self prefersStatusBarHidden];
        [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    }
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}


-(void)viewTapped:(UISwipeGestureRecognizer *)SwipeGr
{
    
    NSLog(@"释放第一响应");
    [UIView animateWithDuration:0.5 animations:^{
        self.xingcheng.frame = CGRectMake(-2 * WIDTH / 3, 64, 2 * WIDTH / 3, HEIGH - 64);
       
        [self.view bringSubviewToFront:self.xingcheng];
        
        
    }completion:^(BOOL finished) {
        [self.xingcheng removeFromSuperview];
    }];
    
    [UIView animateWithDuration:1 animations:^{
        self.button.hidden = NO;
    }];

    
}

-(void)viewTapped2:(UISwipeGestureRecognizer *)SwipeGr{
    
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];

    
}

-(void)creatxingchengview{
    
    self.Totop = [UIButton buttonWithType:UIButtonTypeCustom];
    self.Totop.layer.cornerRadius = 20;
    self.Totop.frame = CGRectMake(WIDTH - 55, HEIGH - 80, 40, 40);
    self.Totop.backgroundColor = [UIColor whiteColor];
    [self.Totop setBackgroundImage:[UIImage imageNamed:@"totop"] forState:UIControlStateNormal];
    [self.Totop addTarget:self action:@selector(totop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.Totop];

    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.layer.cornerRadius = 10;
    self.button.frame = CGRectMake(15,HEIGH - 80, 40, 40);
    
    self.button.backgroundColor = [UIColor whiteColor];
    [self.button setBackgroundImage:[UIImage imageNamed:@"mulu"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(xicheng:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
    
    
    
    
}
#pragma mark 行程界面
-(void)xicheng:(UIButton *)button{
    NSLog(@"形成界面");
    self.xingcheng = [[ViewXingCheng alloc]initWithFrame:CGRectMake(- 2 * WIDTH / 3,64, 2 * WIDTH / 3, HEIGH - 64)];
    self.xingcheng.backgroundColor = [UIColor blackColor];
    
      [self.xingcheng handleDataWith:self.strURl];
    
    [self.view addSubview:self.xingcheng];
   
    
    
    self.labelxingcheng = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 2 / 3, 40)];
    self.labelxingcheng.backgroundColor = [UIColor blackColor];
    [self.xingcheng addSubview:self.labelxingcheng];
    
    self.labelxingcheng.font = [UIFont fontWithName:@"AmericanTypewriter-Bold"size:25];
    self.labelxingcheng.text = @" 行程概述";
    self.labelxingcheng.textColor = [UIColor whiteColor];
    
   
    
    self.redline = [[UIView alloc]initWithFrame:CGRectMake(0, 40, WIDTH * 2 / 3, 2)];
    self.redline.backgroundColor = [UIColor grayColor];
    
    [self.xingcheng addSubview:self.redline];
    
    
   [UIView animateWithDuration:0.5 animations:^{
       self.xingcheng.frame = CGRectMake(0, 64, 2 * WIDTH / 3, HEIGH - 64);
   }];
    
  [UIView animateWithDuration:1 animations:^{
      self.button.hidden = YES;
  }];
    
    [self.redline release];
    [self.xingcheng release];
    [self.labelxingcheng release];
    
    
}

#pragma mark 回到顶部

-(void)totop:(UIButton *)button{
    
    [self.tabview setContentOffset:CGPointMake(0,0) animated:YES];
    
}



#pragma mark - handleData
- (void)handleData {
//    NSLog(@"%@",self.strURl);
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:self.strURl];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            //NSLog(@"OBJECT: %@123",responseObject);
            NSArray *arrTripDays = [responseObject objectForKey:@"trip_days"];
            self.dic = [NSMutableDictionary dictionary];
            
            for (NSDictionary *dic in arrTripDays) {
                NSNumber *day = [dic objectForKey:@"day"];
                NSInteger dayInt = [day integerValue];
                NSString *date = [dic objectForKey:@"trip_date"];
                NSString *key = [NSString stringWithFormat:@"DAY%02ld  %@",dayInt,date];
                NSArray *arrNodes = [dic objectForKey:@"nodes"];
                
                NSMutableArray *array = [NSMutableArray array];
                for (NSDictionary *dicInNodes in arrNodes) {
                    NSArray *arrInNotes = [dicInNodes objectForKey:@"notes"];
                    NSString *entry_type = [dicInNodes objectForKey:@"entry_type"];
                    NSString *entry_name = [dicInNodes objectForKey:@"entry_name"];
                    NSString *attraction_type = [dicInNodes objectForKey:@"attraction_type"];
                    for (NSDictionary *dicModle in arrInNotes) {
                        ModelOfEssay *model = [[ModelOfEssay alloc] init];
                        [model setValuesForKeysWithDictionary:dicModle];
                        model.entry_name = entry_name;
                        model.entry_type = entry_type;
                        model.attraction_type = attraction_type;
                        model.description_s = [dicModle objectForKey:@"description"];
                        
                        NSDictionary *dicImg = [dicModle objectForKey:@"photo"];
                        model.url = [dicImg objectForKey:@"url"];
                        model.image_height = [dicImg objectForKey:@"image_height"];
                        model.image_width = [dicImg objectForKey:@"image_width"];
                        if (model.url || !([model.description_s isEqual:[NSNull null]]||[model.description_s isEqualToString:@""])) {
                            
                            [array addObject:model];
                            
                        }
                        
                        
                        
                        [model release];
                    }
                    
                }
              
                [self.dic setObject:array forKey:key];
            }
            self.array = [[self.dic allKeys] sortedArrayUsingSelector:@selector(compare:)];
            [self.tabview reloadData];
            
            
        }
        
#if 1
        //NSLog(@"%@",self.array);
        for (NSString *key in self.array) {
            NSArray *arr = [self.dic objectForKey:key];
            for (ModelOfEssay *model in arr) {
                if (model.url&&![model.description_s isEqual:[NSNull null]]&&![model.description_s isEqual:@""]) {
                    //NSLog(@"url:%@",model.url);
//                    NSLog(@"des:%@",model.description_s);
                } else{
                    //NSLog(@"des:%@",model.description_s);
                }
                
            }
        }
#endif
        
        
        
    }];
    [dataTask resume];
    
    
}
#pragma mark - tableView
- (void)createTableView {
    self.tabview = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tabview];
    self.tabview.delegate =self;
    self.tabview.dataSource = self;
    
    self.tabview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tabview registerClass:[CellOfEssay2 class]forCellReuseIdentifier:@"CellOfEssay2"];
    [self.tabview registerClass:[CellOfEssay class] forCellReuseIdentifier:@"CellOfEssay"];
    [_tabview release];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *key = [self.array objectAtIndex:section];
    NSArray *arr = [self.dic objectForKey:key];
    
//       NSLog(@"%@",arr);
    return arr.count;
 
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *key = [self.array objectAtIndex:section];
    
//    NSLog(@"%@",key);
    
    return key;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [self.array objectAtIndex:indexPath.section];
    NSArray *arr = [self.dic objectForKey:key];
    ModelOfEssay *model = [arr objectAtIndex:indexPath.row];
    if (model.url) {
        CellOfEssay *cellOfImg = [tableView dequeueReusableCellWithIdentifier:@"CellOfEssay"];
        self.width = model.image_width.floatValue;
        self.height = model.image_height.floatValue;
        
        self.xHeight = self.height * (self.view.frame.size.width - 30)/self.width;
        [cellOfImg passAnyModel:model];
        if (![model.description_s isEqual:[NSNull null]]&&![model.description_s isEqual:@""]) {
            self.Lheight = [CellOfEssay heightForLabel:model.description_s];
            
        }
        
        cellOfImg.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],  [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
        
        
        return cellOfImg;
    } else{
        CellOfEssay2 *cell = [tableView dequeueReusableCellWithIdentifier:@"CellOfEssay2"];
        [cell passModel:model];
        
          cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],  [UIColor colorWithRed:0.16 green:0.14 blue:0.13 alpha:1]);
        
        return cell;
    }
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *key = [self.array objectAtIndex:indexPath.section];
    NSArray *arr = [self.dic objectForKey:key];
    ModelOfEssay *model = [arr objectAtIndex:indexPath.row];
    if (!model.url) {
        CellOfEssay2 *cell = [[CellOfEssay2 alloc] init];
        return [cell heightForCell:model]+ 20;
        
    } else {
        if (![model.description_s isEqual:[NSNull null]]&&![model.description_s isEqual:@""]) {
            
            return self.xHeight + 40 + self.Lheight;
        } else {
            
            return self.xHeight + 40;
        }
    }
}


@end
